package com.woniuxy.third.controller;

import com.woniuxy.third.entity.User;
import com.woniuxy.third.result.ResponseResult;
import com.woniuxy.third.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {
    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);


    @PostMapping("/login")
    public ResponseResult<String> login(@RequestBody User user, HttpServletResponse response, HttpServletRequest request){
        String token = request.getHeader("authorization");
        if (token != null) {
            return new ResponseResult<>(201,"已登陆请勿重新登录",null);
        }

        //逻辑：用账号查询出结果，然后进行对比   假设查询出来
        if (user.getAccount().equals("zhangsan") && user.getPwd().equals("123")){
            logger.debug("登录成功!");
            //生成一个token（JWT）,返回给前端
            token = JwtUtil.generateToken(user.getAccount());

            //将token放到响应头
            response.setHeader("authorization",token);

            //将该响应头暴露给第三方
            response.setHeader("Access-Control-Expose-Headers","authorization");


            return new ResponseResult<>(200,"success",null);
        }else {
            logger.debug("登录失败!");
            return new ResponseResult<>(500,"账号或者密码有误",null);
        }
    }
}
